--
-- Author: mm
-- Date: 2018-03-24 15:57:03
--
-- NewguildSearchView
-- 工会列表、查找UI

local NewguildRender = import(".renders.NewguildRender")
local NewguildIconRender = import(".renders.NewguildIconRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.NewGuildListUI

local MAX_WORD_LEN = tonumber( GD:getSystemPar( "guildNameLength", 6 ) ) -- 公会名字最长字符数
local SEARCH_CD = 3 -- 搜索具体目标CD时间
local _searchPanelShowFlag = false -- 创建panel显示之前 _searchPanel 的显示状态
local _guildInfoPanelShowFlag = false -- 创建panel显示之前 _guildInfoPanel 的显示状态
local guildRecruitTextWidth = 0 -- 公会招募宣言文本控件默认宽度
local guildRecruitTextHeight = 0 -- 公会招募宣言文本控件默认高度

function ClassRef:init()
	self._searchPanel = self._ui["Panel"] -- 搜索panel
	self._searchPanel:setVisible( true )

	self._searchPanel:getChildByName( "Button_close" ):addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)

	self._searchPanel:findChild( "Panel_mid/Button_queding" ):addClickEventListener(function()
		self:_showPreCreateGuild()
	end)
	self._searchPanel:findChild( "Panel_mid/Button_shenqing" ):addClickEventListener(function()
		executeFunc( self._onOperate, "quickAddGuild" )
	end)

	-- 公会列表ListView
	local params = {
		renderClass = NewguildRender,
		perNum = 1,
		cellEventProxy = function(eventName, params)
			if eventName == "selected_Guild" then
				executeFunc(self._onOperate, "selected_Guild", params)
			elseif eventName == "applyJoin_Guild" then
				executeFunc(self._onOperate, "applyJoin_Guild", params)
			end
		end,
		allEventListen = function(sender, eventType)
			--ccui.ScrollviewEventType.bounceBottom
			local str = self._editText:getText()
			local ulen = string.ulen(str)

			if ulen == 0 then
				if eventType == ccui.ScrollviewEventType.bounceBottom then
					executeFunc(self._onOperate, "reqGuildListEnd")
				elseif eventType == ccui.ScrollviewEventType.bounceTop then
					executeFunc(self._onOperate, "reqGuildListStart")
				end
			end
		end,
	}

	self._guildList = ListViewVertical.new( self._searchPanel:findChild( "Panel_mid/ScrollView" ), params )
	self:initSearch()

	self._guildInfoPanel = self._ui["Panel_tips"] -- 公会信息panel
	self._guildInfoPanel:setVisible( false )
	-- display.nodeRemoveForNotHit( self._guildInfoPanel, function()
	-- 	self._guildInfoPanel:setVisible( false )
	-- end )

	self._guildInfoIcon = NewguildIconRender.create( self._guildInfoPanel:getChildByName( "icon" ) )
	self._guildInfoName = self._guildInfoPanel:getChildByName( "name" )
	self._guildInfoScrollView = self._guildInfoPanel:getChildByName( "ScrollView_1" )
	guildRecruitTextWidth, guildRecruitTextHeight = self._guildInfoScrollView:getContentSize2()
	self._guildInfoText = self._guildInfoScrollView:getChildByName( "text" ) -- 招募宣言

	self._guildPanel = self._ui["Panel_build"] -- 创建预览panel
	self._guildPanel:setVisible( false )

	self._costText = self._guildPanel:findChild( "Panel_mid/num" )
	local costData = UD:parseRewardToBagItem(GD:getSystemStrPar("guildCreateCost"))
	self._guildPanel:findChild( "Panel_mid/icon" ):loadTexture(costData:getSmallIcon())
	self._costText:setString( tostring(costData:getAmount()) )

	local ownDaibi = UD:getDaibiValue(costData:getId())
	self._guildPanel:findChild("Panel_coin/num"):setString( tostring(ownDaibi) ) -- 拥有金币
	self._guildPanel:findChild("Panel_coin/icon"):loadTexture(costData:getSmallIcon())

	self._guildPanel:findChild( "Panel_coin" ):addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            local param = {itemId = costData:getId(),tipsType = Enums.TipsType.daibi}
            local boundingBoxTemp = sender:getBoundingBox()
            local worldPosTemp = sender:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
            boundingBoxTemp.x = worldPosTemp.x
            boundingBoxTemp.y = worldPosTemp.y
            param.boundingBox = boundingBoxTemp
            app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
        end
	end)

	self._guildPanel:findChild( "Panel_mid/Button_queding" )
	self._guildPanel:findChild( "Panel_mid/Button_queding" ):addClickEventListener(function()
		executeFunc( self._onOperate, "preCreata_guild" )
	end)
	self._guildPanel:findChild( "Panel_mid/Button_quxiao" ):addClickEventListener(function()
		self:_hidePreCreateGuild()
	end)
	self._guildPanel:findChild( "Button_close" ):addClickEventListener(function()
		self:_hidePreCreateGuild()
	end)
end

-- 返回搜索内容
function ClassRef:getSearchText()
	return self._editText:getText()
end

-- 工会搜索框 处理
function ClassRef:initSearch()
	local function onEditCallback(strEventName,sender)
		local edit = sender
		if strEventName == "changed" then
			local text = edit:getText()
			local ulen = string.ulen(text)
			if ulen > MAX_WORD_LEN then
				local newStr = string.usubstr(text,MAX_WORD_LEN)
				if text~=newStr then
					edit:setText(newStr)
					text = newStr
					display.pushToast(string.format(L("max_input_char"), MAX_WORD_LEN))
				end
			end
		end
	end

	local searchTextPanel = self._searchPanel:findChild( "Panel_mid/Panel_search" )

	local tf = searchTextPanel:getChildByName("TextField")
	self._editText = display.replaceTextFieldWithEditBox(tf)
	self._editText:setPlaceholderFontColor(cc.c4b(168,141,91,255))
	self._editText:registerScriptEditBoxHandler(onEditCallback)

	self._searchCloseBtn = searchTextPanel:getChildByName("Button_close")
	self._searchCloseBtn:addClickEventListener(function(sender)
		self._editText:setText("")
		self._searchBtn:setVisible( true )
		self._searchCloseBtn:setVisible( false )

		executeFunc(self._onOperate, "closeSearch_guild")
	end)


	self._searchBtn = searchTextPanel:getChildByName("Button_enter")
	self._searchBtn:addClickEventListener(function(sender)
		local str = self._editText:getText()
		if string.len(str) > 0 then
			self._searchBtn:setVisible( false )
			self._searchCloseBtn:setVisible( true )

			executeFunc(self._onOperate, "search_guild", str)

			-- protect 3s
			display.setBtnTouchEnable(sender, false)
			sender:performWithDelay(function()
				display.setBtnTouchEnable(sender, true)
			end, SEARCH_CD)
		end
	end)
end

-- 刷新选择的公会具体信息
-- guildInfo = NewguildInfo
function ClassRef:refreshGuildInfo( guildInfo )
	if not self._guildInfoPanel:isVisible() then -- 不可见？
		self._guildInfoPanel:setVisible( true )
		self:playAction("tips", false)
	end

	self._guildInfoIcon:setData( guildInfo:getGuildIcon() )
	self._guildInfoName:setString( guildInfo:getGuildName() )

	local guildDesc = guildInfo:getGuildDesc()
	self._guildInfoText:getVirtualRenderer():setDimensions( guildRecruitTextWidth, 0 )
	if "" ~= guildDesc then
		self._guildInfoText:setString( guildDesc )
	else
		self._guildInfoText:setString( L("guild_default_notice") )
	end
	local textRenderSize = self._guildInfoText:getVirtualRendererSize()
	self._guildInfoText:setContentSize( cc.size( guildRecruitTextWidth, textRenderSize.height ) )
	self._guildInfoText:setPositionY( textRenderSize.height )
	self._guildInfoScrollView:getInnerContainer():setContentSize( cc.size( guildRecruitTextWidth, textRenderSize.height ) )
	self._guildInfoScrollView:getInnerContainer():setPositionY( guildRecruitTextHeight - textRenderSize.height )
	self._guildInfoScrollView:setTouchEnabled( textRenderSize.height > guildRecruitTextHeight )
end

-- 显示创建公会预览panel
function ClassRef:_showPreCreateGuild()
 	_searchPanelShowFlag = self._searchPanel:isVisible()
 	_guildInfoPanelShowFlag = self._guildInfoPanel:isVisible()

	self._searchPanel:setVisible( false )
	self._guildInfoPanel:setVisible( false )

	if not self._guildPanel:isVisible() then -- 不可见？
		self._guildPanel:setVisible( true )
		self:playAction("build", false)
	end


	local costData = UD:parseRewardToBagItem(GD:getSystemStrPar("guildCreateCost"))
	local ownDaibi = UD:getDaibiValue(costData:getId())

	if tonumber(ownDaibi) >= costData:getAmount() then
		self._costText:setTextColor(cc.c3b(47, 12, 4) )
	else
		self._costText:setTextColor(display.COLOR_RED )
	end
	
	display.setBtnTouchEnable( self._guildPanel:findChild( "Panel_mid/Button_queding" ), tonumber(ownDaibi) >= costData:getAmount() )
end
-- 隐藏创建公会预览panel
function ClassRef:_hidePreCreateGuild()
	self._guildPanel:setVisible( false )

	self._searchPanel:setVisible( _searchPanelShowFlag )
	self._guildInfoPanel:setVisible( _guildInfoPanelShowFlag )
end

function ClassRef:refreshGuildData(listData, deltalLen)
	self._guildList:reloadData(listData)
	if deltalLen <= 0 then
		deltalLen = 1
	elseif deltalLen >= #listData then
		deltalLen = #listData
	end

	self._guildList:jumpToIndex(deltalLen)
end

function ClassRef:refreshGuildDataOnly(listData)
	self._guildList:refreshData(listData)
end

function ClassRef:checkGuide()
	local params = {
		scene = Constant.FUNC_TYPE_GANG,
		sceneSelf = self,
		getFunc = self.getGuideNodeFunc,
		nextFunc = self.checkGuide
	}
	EM:notify("checkGuide", params)
end

-- 获取引导node
function ClassRef:getGuideNodeFunc(id)

end

return ClassRef
